// miniprogram/pages/index/index.js
const amap = require('../../libs/amap-wx.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    weather:{}, //天气信息
    DeviceList:[], //用户绑定的设备列表
    show: false,
    actions: [
      { name: '绑定设备' },
    ],
  },
  // }, 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.firstLoad();
  },
  //获取天气
  getWeather:async function(){
    let that = this;
    var myAmapFun = new amap.AMapWX({key:'5cafa1133f593cfe005081749a46e717'});
    myAmapFun.getWeather({
      success: function(data){
        console.log(data);
        that.setData({
          weather:data
        })
      },
      fail: function(info){
        //失败回调
        console.log(info)
      }
    })
  },

  //获取用户绑定的设备列表
  getFamilyDeviceList:function(){
    let that = this;
    app.sdk.init().then(()=>{
      app.sdk.requestApi('AppGetFamilyDeviceList',{ FamilyId: 'default' })
      .then((res)=>{
        console.log(res);
        that.setData({
          DeviceList:res.DeviceList
        });
        console.log(that.data.DeviceList);
      })
      .catch((err)=>{
        console.log(err);
      })
    })
  },
  firstLoad:function(){
    let that = this;
    wx.showLoading({
      title: '获取设备中',
      mask:true,
      success:()=>{
        that.getFamilyDeviceList();
        wx.hideLoading();
      }
    })
  },
  //跳转到设备控制页
  goToDeviceControl:function(e){
    const { AliasName } = e.currentTarget.dataset.info;
    let path;
    switch (e.currentTarget.dataset.info.ProductId) {
      case '5JOEOMS1CG' :
        path = 'RGBlight/index';
        break; 
      case '3253P3LS8V' :
        path = 'light/index' ;
        break;
      case 'RX2L28PDE2' :
        path = 'tempHumi/index';
        break;
    }
    wx.navigateTo({
      url: `/pages/deviceControl/${ path }?AliasName=${ AliasName }`,
      success:(res)=>{
        res.eventChannel.emit('getDeviceData',{ data:e.currentTarget.dataset });
      }
    })
  },
  
  //底部弹起的模态面板
  isShow:function(){
    this.setData({
      show:!this.data.show
    })
  },
  onClose:function() {
    this.setData({ show: false });
  },
  onCancel:function(){
    this.setData({ show: false });
  },
  onSelect:function(event) {
    console.log(event.detail);
    wx.navigateTo({
      url: '/pages/addDevice/index',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getWeather();
    this.getFamilyDeviceList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})